package com.hangzhou.xyj.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.event.CorrectRespEvent;
import com.hangzhou.xyj.event.NewMessageEvent;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.UserModel;
import com.hangzhou.xyj.model.type.ECorrectType;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.model.type.EUserType;
import com.hangzhou.xyj.net.handler.GetUserDetailHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.request.GetUserDetailReq;
import com.hangzhou.xyj.net.response.GetUserDetailResp;
import com.hangzhou.xyj.ui.activity.MyFansActivity;
import com.hangzhou.xyj.ui.activity.MyFocusActivity;
import com.hangzhou.xyj.ui.activity.MyPersonalInfoActivity;
import com.hangzhou.xyj.ui.fragment.base.BaseFragment;
import com.hangzhou.xyj.ui.widget.CircleImageView;
import com.hangzhou.xyj.ui.widget.ClickItemView;
import com.hangzhou.xyj.ui.widget.views.MyImageView;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.LogUtil;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.hyphenate.chat.EMClient;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 我
 *
 * @author neo.duan
 */
public class MineFragment extends BaseFragment implements OnClickListener {
    CircleImageView mIvHeadImg;//头像
    MyTextView mTvFocusNum;//关注数
    MyTextView mTvFansNum;//粉丝数
    MyTextView mTvDynamicNum;//动态数
    MyTextView mTvSign;//签名
    MyTextView mTvNickName;//昵称
    MyImageView mIvAuthen;//认证标识
    LinearLayout mLlPersinalInfo;//个人信息条
    MyImageView mIvGender;//性别

    private ClickItemView mMessageItemView;

    public MineFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBusUtil.register(this);
        return super.onCreateView(inflater, container, savedInstanceState);

    }

    @Override
    public void initTop() {
        enableTop(false);
        enableRefresh(false);
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.fragment_mine);
    }

    @Override
    public void initViews() {
        mTvFocusNum = findView(R.id.mtv_focus_num);
        mTvFansNum = findView(R.id.mtv_fans_num);
        mTvDynamicNum = findView(R.id.mtv_dynamic_num);
        mTvSign = findView(R.id.mtv_sign);
        mTvNickName = findView(R.id.nick_name);
        mIvHeadImg = findView(R.id.civ_header);
        mIvAuthen = findView(R.id.miv_authen);
        mLlPersinalInfo = findView(R.id.ll_my_personal_info);
        mIvGender = findView(R.id.gender);
        mMessageItemView = findView(R.id.view_my_message);
    }

    @Override
    public void initDatas() {
        UserModel userModel = XYJApplication.getUserInfo();
        setData(userModel);
    }


    @Override
    public void initListeners() {
        findView(R.id.miv_mine_bg).setOnClickListener(this);
        findView(R.id.ll_personal_info).setOnClickListener(this);
        findView(R.id.civ_setting).setOnClickListener(this);
        findView(R.id.ll_my_active).setOnClickListener(this);
        findView(R.id.ll_my_focus).setOnClickListener(this);
        findView(R.id.ll_my_fans).setOnClickListener(this);
        findView(R.id.civ_my_collection).setOnClickListener(this);
        findView(R.id.view_my_message).setOnClickListener(this);
        findView(R.id.civ_my_comment).setOnClickListener(this);
        findView(R.id.civ_my_group).setOnClickListener(this);
        findView(R.id.civ_share_version).setOnClickListener(this);
//        findView(R.id.civ_test_api).setOnClickListener(this);
        mLlPersinalInfo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.miv_mine_bg:
//                ToastUtil.show("点击更换背景图片");
                break;
            case R.id.ll_my_personal_info:
            case R.id.ll_personal_info:
                Intent intent = new Intent(mContext, MyPersonalInfoActivity.class);
                intent.putExtra(DataKey.INTENT_TAG, EIntentTagType.TAG_MINE.getValue());
                IntentManager.getInstance().goActivity(
                        mContext, intent);
                break;
            case R.id.civ_setting:
                IntentManager.getInstance().goMineSettingActvitity(mContext);
                break;
            case R.id.civ_my_collection:
                IntentManager.getInstance().goMineCollectionActivity(mContext);
                break;
            case R.id.view_my_message:
                //点击了，隐藏红色小红点
                View redPointView = v.findViewById(R.id.tv_mine_red_point);
                if (redPointView.getVisibility() == View.VISIBLE) {
                    redPointView.setVisibility(View.GONE);
                }
                IntentManager.getInstance().goMineMessageActivity(mContext);
                break;
            case R.id.civ_my_comment:
                IntentManager.getInstance().goMineCommentActivity(mContext);
                break;
            case R.id.ll_my_active:
                IntentManager.getInstance().goMyActiveActivity(mContext);
                break;
            case R.id.ll_my_focus:
                IntentManager.getInstance().goMyFocusActivity(mContext, new Intent(mContext, MyFocusActivity.class));
                break;
            case R.id.ll_my_fans:
                IntentManager.getInstance().goMyFansActivity(mContext, new Intent(mContext, MyFansActivity.class));
                break;
            case R.id.civ_my_group:
                IntentManager.getInstance().goMyGroupActivity(mContext);
                break;
            case R.id.civ_share_version:
                //分享版本
                PublicUtil.showShareVersion(null);
                break;
            default:
                break;
        }
    }


    private void setData(UserModel data) {
        mTvFocusNum.setText(String.valueOf(data.getFollowNum()));//关注数
        mTvFansNum.setText(String.valueOf(data.getFansNum()));//粉丝数
        mTvDynamicNum.setText(String.valueOf(data.getDynamicNum()));//动态数
        mTvSign.setText(data.getSignature());//签名
        mTvNickName.setText(data.getNickName());//昵称
        updateGenderIcon(data.getSex());
        mIvHeadImg.displayImage(XYJApplication.getUserInfo().getHeadPic());
        //设置用户认证图标
        EUserType userType = data.getUserType();
        mIvAuthen.displayImage(PublicUtil.getAuthenIconStringUri(mContext, userType));
    }

    @Override
    public void onResume() {
        super.onResume();
        //获取消息，如果有消息，则显示小红点
        int unreadMsgsCount = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        mMessageItemView.setRedDotDisplay(unreadMsgsCount > 0);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }

    @Subscribe
    public void onEventMainThread(CorrectRespEvent event) {
        switch (ECorrectType.valueOf(event.getTag())) {
            case HEAD_IMG:
                mIvHeadImg.displayImage("file://" + event.getValue());
                break;
            case GENDER:
                updateGenderIcon(event.getValue());
                break;
            case SIGN:
                mTvSign.setText(event.getValue());
                break;
            case NAME:
                mTvNickName.setText(event.getValue());
                break;
        }
    }

    /**
     * 更新性别图标
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/19 16:20
     */
    public void updateGenderIcon(String gender) {
        if (StringUtil.isNotEmpty(gender)) {
            switch (gender) {
                case "女":
                    mIvGender.setImageResource(R.drawable.female);
                    break;
                case "男":
                default:
                    mIvGender.setImageResource(R.drawable.male);
                    break;
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) { //页面显示
            updateUserInfo();
        }
    }

    /**
     * 收到新消息事件，更新小红点
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNewMessageEvent(NewMessageEvent event) {
        LogUtil.d(TAG, "收到新消息");
        mMessageItemView.setRedDotDisplay(true);
    }

    /**
     * 更新用户信息
     */
    public void updateUserInfo() {
        //向服务器请求数据
        String userId = XYJApplication.getUserInfo().getUserId();
        GetUserDetailReq getUserDetailReq = new GetUserDetailReq(Integer.valueOf(userId), Integer.valueOf(userId));
        HttpLoader.getInstance().sendRequest(new GetUserDetailHandler(getUserDetailReq, new MyHttpResponseListener() {
            @Override
            public void onStart() {
                //不要加载框
            }

            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                hideLoadingDialog();//隐藏Loading对话框
                GetUserDetailResp.UserDetail detail = (GetUserDetailResp.UserDetail) model;
                UserModel userModel = detail.getUserInfo();
                UserModel currentUserInfo = XYJApplication.getUserInfo();
                //更新
                currentUserInfo.setHeadPic(userModel.getHeadPic());
                currentUserInfo.setNickName(userModel.getNickName());
                currentUserInfo.setSignature(userModel.getSignature());
                currentUserInfo.setFollowNum(userModel.getFollowNum());
                currentUserInfo.setFansNum(userModel.getFansNum());
                currentUserInfo.setDynamicNum(userModel.getDynamicNum());
                currentUserInfo.setCheckFlag(userModel.getCheckFlag());
                initDatas();
            }
        }, 0));
    }
}
